"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 硬件故障类--network
Case Name   : 执行事务时，备节点注入网络错包故障，错包率3%
Create At   : 2021/07/28
@zou_jialiang0505328126
Description :
    1.注入网络错包故障
    2.创建表并插入数据
    3.执行TPCC
    4.检查主备一致性
Expect      :
    1.成功
    2.成功
    3.成功
    4.checksum结果一致
History     :
    Modified by @wan005 2021/11/1:调整故障清理位置
    Modified by @wan005 2022/2/27:网络错包会导致环境SSH异常，调整错包率规避该问题
"""

import unittest
import time
from yat.test import Node, macro
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Logger import Logger


class DiskIOwait(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('----Opengauss_Reliability_Hardware_Case067:开始执行----')
        self.primary_root_node = Node(node='PrimaryRoot')
        self.sta1_root_node = Node(node='Standby1Root')
        self.primary_user_node = Node(node='PrimaryDbUser')
        self.sta1_dbuser = Node(node='Standby1DbUser')
        self.sta2_dbuser = Node(node='Standby2DbUser')
        self.com = Common()
        self.constant = Constant()
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.sta_1_sh = CommonSH('Standby1DbUser')
        self.sta_2_sh = CommonSH('Standby2DbUser')
        self.tbname = "network_card"

        self.log.info('----获取网卡----')
        network_card_cmd = 'ifconfig'
        self.log.info(network_card_cmd)
        network_card_result = self.sta1_root_node.sh(
            network_card_cmd).result()
        network_card_list = network_card_result.split('\n\n')
        self.log.info(network_card_list)
        self.networkcard = ''
        for network_card_item in network_card_list:
            if self.sta1_dbuser.db_host in network_card_item:
                self.networkcard = network_card_item.split(':')[0].strip()
                self.log.info(self.networkcard)

    def test_main(self):
        self.log.info("--------------1.注入网络错包故障-------------")
        inject_command = f"rNet_corrupt " \
            f"(dev, rate)values({self.networkcard}, " \
            f"{self.constant.network_error_rate})"
        result = self.com.cfe_inject(self.sta1_root_node, inject_command)
        self.log.info(result)
        result = self.com.cfe_query(self.sta1_root_node,
                                    f"rNet_corrupt where "
                                    f"dev={self.networkcard}")
        self.log.info(result)
        self.assertIn(f"corrupt {self.constant.network_error_rate}", result)

        self.log.info("------2. 创建表并插入数据-----------")
        sql = f"create table {self.tbname}(i int);" \
            f"insert into {self.tbname} values(generate_series(1,10000));"
        result = self.primary_sh.executDbSql(sql)
        self.log.info(result)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, result)
        self.assertIn("INSERT", result)

        self.log.info("------------3.执行TPCC----------------")
        result = self.com.startTPCC(self.primary_root_node, macro.TPCC_PATH)
        self.log.info(result)
        self.assertIn(self.constant.TPCC_SUCCESS_MSG, result)

        self.log.info("------------4.检查数据一致性------------")
        time.sleep(10)
        result = self.com.cfe_clean(self.sta1_root_node,
                                    f"rNet_corrupt where "
                                    f"dev={self.networkcard} and rate="
                                    f"{self.constant.network_error_rate}")
        self.log.info(result)
        result = self.com.cfe_query(self.sta1_root_node,
                                    f"rNet_corrupt where "
                                    f"dev={self.networkcard}")
        self.log.info(result)
        time.sleep(20)
        result = self.sta_1_sh.check_data_consistency()
        self.assertTrue(result)
        result = self.sta_2_sh.check_data_consistency()
        self.assertTrue(result)
        nodes_tuple = (self.primary_user_node,
                       self.sta1_dbuser, self.sta2_dbuser)
        flag = self.com.check_data_sample_by_all(r'\d', *nodes_tuple)
        self.assertTrue(flag)
        time.sleep(10)

        table_dict = self.com.format_sql_result(
            self.primary_sh.executDbSql(r'\d'))
        table_name = table_dict.get('Name')
        for name in table_name:
            select_sql = f'select count(*) from {name};'
            flag = self.com.check_data_sample_by_all(select_sql,
                                                     *nodes_tuple)
            self.assertTrue(flag)
        sql = f"SELECT CHECKSUM({self.tbname}::TEXT) FROM {self.tbname};"
        result1 = self.primary_sh.executDbSql(sql)
        self.log.info(result1)
        result2 = self.sta_1_sh.executDbSql(sql)
        self.log.info(result2)
        result3 = self.sta_2_sh.executDbSql(sql)
        self.log.info(result3)
        self.assertEqual(result1, result2)
        self.assertEqual(result1, result3)

    def tearDown(self):
        self.log.info("--------------备节点清理故障-------------")
        result = self.com.cfe_clean(self.sta1_root_node,
                                    f"rNet_corrupt where "
                                    f"dev={self.networkcard} and rate="
                                    f"{self.constant.network_error_rate}")
        self.log.info(result)
        result = self.com.cfe_query(self.sta1_root_node,
                                    f"rNet_corrupt where "
                                    f"dev={self.networkcard}")
        self.log.info(result)
        self.log.info("-----------删除表---------------")
        sql = f"drop table if exists {self.tbname}"
        result = self.primary_sh.executDbSql(sql)
        self.log.info(result)
        self.log.info('---Opengauss_Reliability_Hardware_Case067:执行完成---')
